/*
 * $Id$
 *
 * Copyright 2008 HuangHuang. All rights reserved.
 */

package com.crm.web.page;

import org.apache.tapestry.html.BasePage;
import org.apache.tapestry.IPage;
import org.apache.tapestry.event.PageBeginRenderListener;
import org.apache.tapestry.event.PageEvent;
import org.apache.tapestry.form.IPropertySelectionModel;
import org.apache.tapestry.form.StringPropertySelectionModel;
import org.apache.tapestry.annotations.InjectState;
import org.apache.tapestry.annotations.InjectPage;
import org.apache.tapestry.annotations.Bean;
import org.apache.tapestry.annotations.Persist;
import org.apache.tapestry.valid.ValidationConstraint;
import org.apache.tapestry.valid.ValidationDelegate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.javaforge.tapestry.spring.annotations.InjectSpring;
import com.crm.service.IContactService;
import com.crm.model.Contact;
import com.crm.model.User;
import com.crm.model.Customer;
import com.crm.web.util.Tools;
import com.crm.web.util.Constants;

import java.util.Date;
import java.util.Calendar;

/**
 * @author <a href="mailto:huang0510@hotmail.com">HuangHuang</a>
 * @version $Id$
 */
public abstract class ContactNew extends BasePage implements PageBeginRenderListener {

    private static Log log = LogFactory.getLog(ContactNew.class);

    @Bean
    public abstract ValidationDelegate getDelegate();

    @InjectState("userSession")
    public abstract User getUserSession();

    @InjectSpring("contactService")
    public abstract IContactService getContactService();

    @InjectPage("ContactList")
    public abstract ContactList getContactListPage();

    public abstract String getContactName();

    public abstract String getDepartment();

    public abstract String getJobTitle();

    public abstract String getEmail();

    public abstract String getCountryCode();

    public abstract String getAreaCode();

    public abstract String getPhone();

    public abstract String getExtension();

    public abstract String getCountryCodeFax();

    public abstract String getAreaCodeFax();

    public abstract String getFax();

    public abstract String getExtensionFax();

    public abstract String getComment();

    public abstract String getSex();

    @Persist
    public abstract Customer getCustomer();

    public abstract void setCustomer(Customer customer);

    public IPropertySelectionModel getSexModel() {
        return new StringPropertySelectionModel(Constants.SEX_SELECT);
    }

    public IPage infoSubmit() {
        try {
            if (getDelegate().getHasErrors()) {
                return getPage();
            }

            Contact contact = new Contact();
            contact.setContactName(getContactName());
            contact.setSex(getSex());

            String email = getEmail() == null ? "none" : getEmail();
            contact.setEmail(email);

            String position = getJobTitle() == null ? "none" : getJobTitle();
            contact.setJobTitle(position);

            String department = getDepartment() == null ? "none" : getDepartment();
            contact.setDepartment(department);

            String phone = getCountryCode() + "-" + getAreaCode() + "-" + getPhone();
            if (getExtension() != null) {
                phone = phone + "-" + getExtension();
            }
            contact.setPhone(phone);

            String fax = getCountryCodeFax() + "-" + getAreaCodeFax() + "-" + getFax();
            if (getExtensionFax() != null) {
                fax = fax + "-" + getExtensionFax();
            }
            contact.setFax(fax);

            if (phone.length() > 32 || fax.length() > 32) {
                getDelegate().record("电话号码或传真不能超过29个字符", ValidationConstraint.CONSISTENCY);
                return getPage();
            }

            String dateOfSave = Tools.formatDate(new Date(), Tools.DATEANDTIME);
            contact.setDateSave(dateOfSave);

            contact.setUser(getUserSession());

            String weekOfYear = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
            weekOfYear = weekOfYear + String.valueOf(Calendar.getInstance().get(Calendar.WEEK_OF_YEAR));
            contact.setWhichWeek(weekOfYear);

            contact.setCustomer(getCustomer());

            String commentString = getComment() == null ? "none" : getComment();
            contact.setComments(commentString);

            getContactService().create(contact);

            log.info(getUserSession().getUsername() + " : New contact success! \n" + contact.toString());

            return getContactListPage();
        }
        catch (Exception e) {
            String exceptionString = "The exception happened when save contact info : " + e.getMessage();
            log.warn(getUserSession().getUsername() + " : " + exceptionString);
            e.printStackTrace();
            getDelegate().record(exceptionString, ValidationConstraint.CONSISTENCY);
            return getPage();
        }
    }

    public IPage goback() {
        return getContactListPage();
    }

    public void pageBeginRender(PageEvent event) {
        if (null == getUserSession() || null == getCustomer()) {
            event.getRequestCycle().sendRedirect("app?page=SysPageError&service=page");
        }
    }
}
